﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using CMISLibrary.Libraries;
using CMISLibrary;
using System.Threading;
//using DanhMuc.common;
using busDanhMuc;
using BaocaoNPC.common;
using System.Globalization;

namespace NPCUS_DanhMuc.Usercontrols
{
    /// <summary>
    /// Interaction logic for NPC_LIBRARY.xaml
    /// </summary>
    public partial class NPC_LIBRARY : UserControl
    {

        string id = "";
        string ten = "";
        string dienthoai = "";
        string strBtnClick = "";
        string strError = "";
        string strFind = "";
        int intDongFocus = 0;
        int intIDdong = 0;
        long intLIBID = 0;


        DataSet ds;
        DataSet dsNPC_LIBRARY_Entity;
        DataTable dtBindData;
        cls_NPC_LIBRARY cls = new cls_NPC_LIBRARY(); 

        public NPC_LIBRARY()
        {
            InitializeComponent();

            Component.TabIndexManager.RegisterTabManager(this);

            dsNPC_LIBRARY_Entity = new EntitiesDanhMuc.NPC_LIBRARY();
            //dtHienthi = dsNPC_LIBRARY_Entity.Tables["NPC_LIBRARY"].Clone();

            btnThemMoi.IsEnabled = true;
            btnSua.IsEnabled = false;
            btnXoa.IsEnabled = false;
            btnGhi.IsEnabled = false;
            btnHuy.IsEnabled = false;
            btnTimKiem.IsEnabled = true;

            txtLIBNAME.IsEnabled = false;
            txtASSEMBLYNAME.IsEnabled = false;
            txtNAMESPACE.IsEnabled = false;

            btnTimKiem.Focus();

        }

        private bool checkTextBoxIn()
        {
            if (txtLIBNAME.Text.ToString().Trim() == string.Empty)
            {
                txtLIBNAME.Focus();
                return false;
            }

            if (txtASSEMBLYNAME.Text.ToString().Trim() == string.Empty)
            {
                txtASSEMBLYNAME.Focus();
                return false;
            }

            if (txtNAMESPACE.Text.ToString().Trim() == string.Empty)
            {
                txtNAMESPACE.Focus();
                return false;
            }

            return true;
        }


        private void CheckIsEnableButtonSuaXoa()
        {

            if (dgrNPC_LIBRARY.Items.Count > 0)
            {
                if (strBtnClick == "btnThemMoi" || strBtnClick == "SUA")
                {
                    btnSua.IsEnabled = false;
                    btnXoa.IsEnabled = false;
                }
                else
                {
                    btnSua.IsEnabled = true;
                    btnXoa.IsEnabled = true;
                }
            }
            else
            {
                btnSua.IsEnabled = false;
                btnXoa.IsEnabled = false;
            }
        }

        private bool checkPK()
        {
            //cls_NPC_LIBRARY cls = new cls_NPC_LIBRARY();

            //if (strBtnClick == "btnThemMoi")
            //{

            DataSet dsTemp = GlobalServices.Service_NPCUS.select_NPC_LIBRARY_by_LIBID(intLIBID);            

            if (dsTemp != null)
            {
                if (dsTemp.Tables[0].Rows.Count > 0)
                {

                    MessageBox.Show("ID " + intLIBID + " đã tồn tại !");
                    return true;
                }
                else return false;
            }
            else return false;

        }

        private void setCurrentData()
        {
            DataRowView drv = dgrNPC_LIBRARY.SelectedItem as DataRowView;

            if (drv != null)
            {
                if (strBtnClick == "btnThemMoi" || strBtnClick == "SUA")
                {

                }
                else
                {
                    intLIBID = Convert.ToInt64(drv.Row["LIBID"]);

                    txtLIBNAME.Text = drv.Row["LIBNAME"].ToString();

                    txtASSEMBLYNAME.Text = drv.Row["ASSEMBLYNAME"].ToString();

                    txtNAMESPACE.Text = drv.Row["NAMESPACE"].ToString();
                }
            }



        }

        private void setEntity(string strBtnClick)
        {
            try
            {
                dsNPC_LIBRARY_Entity.Tables["NPC_LIBRARY"].Clear();
                DataRow dr = dsNPC_LIBRARY_Entity.Tables["NPC_LIBRARY"].NewRow();
                switch (strBtnClick)
                {
                    case "btnGhi":
                        dr["SUBDIVISIONID"] = "PA";

                        dr["LIBID"] = intLIBID;

                        dr["LIBNAME"] = txtLIBNAME.Text.Trim().ToString();

                        dr["NAMESPACE"] = txtNAMESPACE.Text.Trim().ToString();

                        dr["ASSEMBLYNAME"] = txtASSEMBLYNAME.Text.Trim().ToString();

                        dr["PRIORITY"] = 3;

                        dr["STATE"] = 1;

                        dr["CREATEDDATE"] = DateTime.Now.Date;

                        dr["CREATEDBY"] = "Admin";

                        break;

                    case "btnXoa":
                        dr["SUBDIVISIONID"] = "PA";

                        dr["LIBID"] = intLIBID;

                        dr["LIBNAME"] = txtLIBNAME.Text.Trim().ToString();

                        dr["NAMESPACE"] = txtNAMESPACE.Text.Trim().ToString();

                        dr["ASSEMBLYNAME"] = txtASSEMBLYNAME.Text.Trim().ToString();

                        dr["PRIORITY"] = 3;

                        dr["STATE"] = 1;

                        dr["CREATEDDATE"] = DateTime.Now.Date;

                        dr["CREATEDBY"] = "Admin";

                        break;

                    case "btnTimKiem":
                        dr["SUBDIVISIONID"] = "PA";

                        dr["LIBID"] = -1;

                        if (txtLIBNAME_S.Text.Trim().ToString() != string.Empty)
                        {
                            dr["LIBNAME"] = txtLIBNAME_S.Text.Trim().ToString();
                        }
                        else
                        {
                            dr["LIBNAME"] = " ";
                        }

                        dr["NAMESPACE"] = " ";

                        if (txtASSEMBLYNAME_S.Text.Trim().ToString() != string.Empty)
                        {
                            dr["ASSEMBLYNAME"] = txtASSEMBLYNAME_S.Text.Trim().ToString();
                        }
                        else
                        {
                            dr["ASSEMBLYNAME"] = " ";
                        }

                        dr["PRIORITY"] = 3;

                        dr["STATE"] = 1;

                        dr["CREATEDDATE"] = DateTime.Now.Date;

                        dr["CREATEDBY"] = "Admin";

                        break;
                    case "btnThemMoi":

                        break;
                }
                dsNPC_LIBRARY_Entity.Tables["NPC_LIBRARY"].Rows.Add(dr);
                dsNPC_LIBRARY_Entity.AcceptChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        private void dgrNPC_LIBRARY_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                setCurrentData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void dgrNPC_LIBRARY_PreviewKeyDown(object sender, KeyEventArgs e)
        {

        }

        private void dgrNPC_LIBRARY_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private void btnTimKiem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;

                setEntity("btnTimKiem");
                if (dsNPC_LIBRARY_Entity.Tables["NPC_LIBRARY"].Rows.Count > 0)
                {
                    DataSet dsTemp;
                    dsTemp = GlobalServices.Service_NPCUS.select_NPC_LIBRARY_1by1(dsNPC_LIBRARY_Entity);                    

                    if (dsTemp != null)
                    {
                        strFind = "Yes";
                        DataTable dtHienthi = dsTemp.Tables[0].Copy();

                        if (dtHienthi.Rows.Count > 0)
                        {
                            dgrNPC_LIBRARY.ItemsSource = dtHienthi.DefaultView;

                            //CheckIsEnableButtonSuaXoa();

                            //======= nếu đang sửa -> tìm kiếm -> nếu trả về có dòng đang sửa -> focus về dòng đó trên Grid
                            for (int i = 0; i < dtHienthi.Rows.Count; i++)
                            {
                                if (int.Parse(dtHienthi.Rows[i]["LIBID"].ToString()) == intIDdong)
                                {
                                    intDongFocus = i;
                                }
                                else
                                {
                                    intDongFocus = -1;
                                }
                            }

                            ////====== Focus về dòng đang sửa - nếu có ======
                            //if (strBtnClick == "SUA")
                            //{
                            //    if (intDongFocus != -1)
                            //    {
                            //        dgrNPC_LIBRARY.SelectedIndex = intDongFocus; 
                            //    }
                            //}

                            if (strBtnClick != "btnThemMoi" || strBtnClick != "SUA")
                            {
                                dgrNPC_LIBRARY.SelectedIndex = 0;
                            }


                            CheckIsEnableButtonSuaXoa();
                            this.Cursor = null;
                        }
                    }
                    else
                    {
                        this.Cursor = null;
                        MessageBox.Show("Không tìm thấy theo điều kiện !");
                        strFind = "No";
                        txtLIBNAME_S.Focus();
                        e.Handled = true;
                    }

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void btnThemMoi_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                strBtnClick = "btnThemMoi";

                btnThemMoi.IsEnabled = false;
                btnSua.IsEnabled = false;
                btnXoa.IsEnabled = false;
                btnGhi.IsEnabled = true;
                btnHuy.IsEnabled = true;
                btnTimKiem.IsEnabled = true;

                dgrNPC_LIBRARY.IsEnabled = true;

                txtLIBNAME.IsEnabled = true;
                txtASSEMBLYNAME.IsEnabled = true;
                txtNAMESPACE.IsEnabled = true;


                txtLIBNAME.Clear();
                txtASSEMBLYNAME.Clear();
                txtNAMESPACE.Clear();

                txtLIBNAME.Focus();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void btnSua_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                strBtnClick = "SUA";
                if (strFind == "Yes" && (dgrNPC_LIBRARY.SelectedIndex.ToString() != string.Empty))
                    btnThemMoi.IsEnabled = false;
                btnSua.IsEnabled = false;
                btnXoa.IsEnabled = false;
                btnGhi.IsEnabled = true;
                btnHuy.IsEnabled = true;
                btnTimKiem.IsEnabled = true;
                btnThemMoi.IsEnabled = false;


                dgrNPC_LIBRARY.IsEnabled = true;

                //intDongFocus = dgrNPC_LIBRARY.SelectedIndex;

                // ======= lấy ID của dòng đang sửa ========
                DataRowView drv = dgrNPC_LIBRARY.SelectedItem as DataRowView;
                intIDdong = int.Parse(drv.Row["LIBID"].ToString());

                intLIBID = Convert.ToInt64(drv.Row["LIBID"].ToString());

                txtLIBNAME.IsEnabled = true;
                txtASSEMBLYNAME.IsEnabled = true;
                txtNAMESPACE.IsEnabled = true;

                txtLIBNAME.Focus();

                dgrNPC_LIBRARY.IsEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void btnXoa_Click(object sender, RoutedEventArgs e)
        {
            this.Cursor = null;

            bool bolCheckDelete = false;
            strBtnClick = "XOA";
            if (MessageBox.Show("Bạn có chắc chắn xoá bản ghi có mã " + intLIBID.ToString() + " không?", "Thông báo", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                setEntity("btnXoa");
                intDongFocus = dgrNPC_LIBRARY.SelectedIndex;

                bolCheckDelete = GlobalServices.Service_NPCUS.delete_NPC_LIBRARY(dsNPC_LIBRARY_Entity, ref strError);
                
                if (bolCheckDelete == true)
                {
                    this.Cursor = null;
                    DataRowView drv = dgrNPC_LIBRARY.SelectedItem as DataRowView;
                    if (drv != null)
                    {
                        drv.Delete();
                        //dtHienthi.AcceptChanges();
                        MessageBox.Show("Xoá dữ liệu thành công!", "Thông báo", MessageBoxButton.OK);
                    }

                    //string idgia = txtIDgia.Text.ToString();
                    //for(int i =0; i< dtBindData.Rows.Count; i++)
                    //{
                    //    if(dtBindData.Rows[i]["INPC_LIBRARY"].ToString() == idgia)
                    //    {                            
                    //        dtBindData.Rows.Remove(dtBindData.Rows[i]);
                    //        dtBindData.AcceptChanges();
                    //    }
                    //}
                }
                else
                {
                    this.Cursor = null;
                    if (strError.Contains("ORA-02292") == true)
                    {
                        MessageBox.Show("Mã số " + intLIBID.ToString() + " đã được sử dụng. Không thể xoá bản ghi này.", "Thông báo", MessageBoxButton.OK);
                    }
                }
            }
            CheckIsEnableButtonSuaXoa();
            strBtnClick = "";
            if (dgrNPC_LIBRARY.Items.Count > intDongFocus)
            {
                dgrNPC_LIBRARY.SelectedIndex = intDongFocus;
            }
            else dgrNPC_LIBRARY.SelectedIndex = intDongFocus - 1;
            btnXoa.Focus();

        }

        private void btnHuy_Click(object sender, RoutedEventArgs e)
        {
            btnThemMoi.IsEnabled = true;
            btnGhi.IsEnabled = false;
            btnHuy.IsEnabled = false;
            btnTimKiem.IsEnabled = true;

            if (dgrNPC_LIBRARY.Items.Count > 0)
            {
                btnSua.IsEnabled = true;
                btnXoa.IsEnabled = true;
            }
            else
            {
                btnSua.IsEnabled = false;
                btnXoa.IsEnabled = false;
            }

            setCurrentData();

            if (strBtnClick == "SUA")
            {
                btnSua.Focus();
            }
            else
                if (strBtnClick == "btnThemMoi")
                {
                    btnThemMoi.Focus();
                }

            txtLIBNAME.IsEnabled = false;
            txtASSEMBLYNAME.IsEnabled = false;
            txtNAMESPACE.IsEnabled = false;

            dgrNPC_LIBRARY.IsEnabled = true;
            strBtnClick = "";
        }


        private void btnGhi_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;

                bool checkInsert = false;

                // ========= Kiem tra du lieu nhap moi ========
                while (checkTextBoxIn() == false)
                {
                    this.Cursor = null;
                    return;
                }


                // ======= Thêm mới -> lấy nextSeq ======
                if (strBtnClick == "btnThemMoi")
                {
                    long nextSeq = 0;
                    nextSeq = GlobalServices.Service_NPCUS.GetNextSequence_Library(ref strError);                    
                    intLIBID = nextSeq;
                }

                // ======== Them moi -> kiem tra PK ========
                if (strBtnClick == "btnThemMoi")
                {
                    if (checkPK() == true)
                    {
                        this.Cursor = null;
                        MessageBox.Show("ID đã tồn tại!");
                        return;
                    }
                }

                setEntity("btnGhi");
                if (strBtnClick == "btnThemMoi")
                {
                    checkInsert = GlobalServices.Service_NPCUS.insert_NPC_LIBRARY(dsNPC_LIBRARY_Entity, ref strError);                    

                }
                else
                {
                    checkInsert = GlobalServices.Service_NPCUS.update_NPC_LIBRARY(dsNPC_LIBRARY_Entity, ref strError);                    
                }


                // ===== Kiem tra Insert , Update thanh cong ? ===

                if (checkInsert == true)
                {
                    this.Cursor = null;

                    dgrNPC_LIBRARY.IsEnabled = true;

                    DataTable dtHienthi = dsNPC_LIBRARY_Entity.Tables["NPC_LIBRARY"].Clone();


                    //=== Xu ly giao dien =====

                    if (dgrNPC_LIBRARY.Items.Count > 0)
                    {  //===== truong hop Grid dang co du lieu hien thi -> lay du lieu vao dtHienthi =====

                        DataView dv = dgrNPC_LIBRARY.ItemsSource as DataView;
                        DataRow[] drselect = dv.Table.Select();
                        foreach (DataRow dr1 in drselect)
                        {
                            dtHienthi.ImportRow(dr1);
                        }
                        dtHienthi.AcceptChanges();
                    }


                    if (strBtnClick == "btnThemMoi")
                    { //====== them dong moi Insert vao dtHienthi =========
                        MessageBox.Show("Thêm mới thành công !");
                        DataTable dtTemp = dsNPC_LIBRARY_Entity.Tables["NPC_LIBRARY"].Copy();
                        DataRow dr = dsNPC_LIBRARY_Entity.Tables["NPC_LIBRARY"].Rows[0];

                        //== them dong moi vao dataBind
                        //dtBindData.ImportRow(dr);
                        //dtBindData.AcceptChanges();


                        dr["SUBDIVISIONID"] = "PA";

                        dr["LIBID"] = intLIBID;

                        dr["LIBNAME"] = txtLIBNAME.Text.Trim().ToString();

                        dr["NAMESPACE"] = txtNAMESPACE.Text.Trim().ToString();

                        dr["ASSEMBLYNAME"] = txtASSEMBLYNAME.Text.Trim().ToString();

                        dr["PRIORITY"] = 3;

                        dr["STATE"] = 1;

                        dr["CREATEDDATE"] = DateTime.Now.Date;

                        dr["CREATEDBY"] = "Admin";

                        dtHienthi.ImportRow(dr);
                        dtHienthi.AcceptChanges();
                        intDongFocus = dtHienthi.Rows.Count - 1;
                    }
                    else
                    {
                        MessageBox.Show("Sửa thành công !");


                        //DataRow dr = dtHienthi.NewRow();
                        //======  sua thanh cong -> hien thi lai du lieu cua dong da sua len Grid  ======
                        for (int i = 0; i < dtHienthi.Rows.Count; i++)
                        {
                            if (Convert.ToInt32(dtHienthi.Rows[i]["LIBID"].ToString()) == intLIBID)
                            {
                                dtHienthi.Rows[i]["SUBDIVISIONID"] = "PA";

                                dtHienthi.Rows[i]["LIBNAME"] = txtLIBNAME.Text.Trim().ToString();

                                dtHienthi.Rows[i]["NAMESPACE"] = txtNAMESPACE.Text.Trim().ToString();

                                dtHienthi.Rows[i]["ASSEMBLYNAME"] = txtASSEMBLYNAME.Text.Trim().ToString();

                                dtHienthi.Rows[i]["PRIORITY"] = 3;

                                dtHienthi.Rows[i]["STATE"] = 1;

                                dtHienthi.Rows[i]["CREATEDDATE"] = DateTime.Now.Date;

                                dtHienthi.Rows[i]["CREATEDBY"] = "Admin";

                                intDongFocus = i;
                            }
                        }

                    }


                    dgrNPC_LIBRARY.ItemsSource = dtHienthi.DefaultView;
                    //if (dtBindData != null)
                    //{
                    //    dtBindData.Clear();
                    //}
                    //dtBindData = dtHienthi.Copy();
                    dgrNPC_LIBRARY.SelectedIndex = intDongFocus;

                    btnThemMoi.IsEnabled = true;
                    btnSua.IsEnabled = true;
                    btnXoa.IsEnabled = true;
                    btnGhi.IsEnabled = false;
                    btnHuy.IsEnabled = false;
                    btnTimKiem.IsEnabled = true;

                    txtLIBNAME.IsEnabled = false;
                    txtASSEMBLYNAME.IsEnabled = false;
                    txtNAMESPACE.IsEnabled = false;


                    if (strBtnClick == "SUA")
                    {
                        btnSua.Focus();
                    }
                    if (strBtnClick == "btnThemMoi")
                    {
                        btnThemMoi.Focus();
                    }

                    strBtnClick = "";
                    dgrNPC_LIBRARY.IsEnabled = true;
                }
                else
                {
                    this.Cursor = null;
                    MessageBox.Show("Không ghi được dữ liệu !");
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }


        private void txtASSEMBLYNAME_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private void txtASSEMBLYNAME_LostFocus(object sender, RoutedEventArgs e)
        {

        }

        private void txtASSEMBLYNAME_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void txtLIBNAME_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private void txtLIBNAME_LostFocus(object sender, RoutedEventArgs e)
        {

        }

        private void txtLIBNAME_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void txtASSEMBLYNAME_S_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private void txtASSEMBLYNAME_S_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void txtLIBNAME_S_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private void txtLIBNAME_S_KeyDown(object sender, KeyEventArgs e)
        {

        }
    }
}
